package com.jishucai;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 */
public class SomeServerHandler extends ChannelInboundHandlerAdapter {

    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 获取向服务器发送消息的Channel
        Channel channel = ctx.channel();
        group.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + " : " + msg + "\n");
            } else {
                channel.writeAndFlush("me : " + msg + "\n");
            }
        });



//        group.writeAndFlush("地址:" + channel.remoteAddress() + ":\n"+msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "=== 上线了 ");
        group.writeAndFlush(ctx.channel().remoteAddress() + "上线了\n");
        group.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "=== 下线了 ");
        group.writeAndFlush(ctx.channel().remoteAddress() + "下线了\n");
//        group.remove(ctx.channel());
    }
}
